#include "ChannelPropertiesWindow.h"
#include "main.h"
#include "AdminManager.h"

ChannelPropertiesWindow::ChannelPropertiesWindow(QWidget *parent)
 :QWidget() , _parent(parent), _channel(0)
{
	setWindowIcon(QIcon("./images/Agora.png"));
	tempDisplay(this);
	initRightsList();
	this->show();
}

void ChannelPropertiesWindow::tempDisplay(QWidget *dest)
{
	// Creation du QTabWidget
    onglets = new QTabWidget(dest);
	
	 
    onglets->setGeometry(0, 0, 700, 300);
	//TODO ... set resizable(false)
	dest->setMinimumSize(700, 300);
	dest->setMaximumSize(700, 300);
    // Creation des pages
    page1 = new QWidget;
	page2 = new QWidget;
	page3 = new QWidget;

	// Creation du contenu des pages de widgets
        // Page 1
	QGridLayout *page1Layout = new QGridLayout;
	QPushButton* buttonSaveChan = new QPushButton("Save", page1);
	connect(buttonSaveChan, SIGNAL(clicked()), this, SLOT(saveChan()));
	QGroupBox *chanInfoBox = new QGroupBox(page1);
	chanInfoBox->setTitle("Channel's Informations");
	//chanInfoBox->setGeometry(15, 40, 320, 140);
	QVBoxLayout	*chanInfoVBox = new QVBoxLayout();
	QGroupBox *chanPassBox = new QGroupBox(page1);
	chanPassBox->setTitle("Channel's Password");
	//chanPassBox->setGeometry(355, 40, 320, 140);
	QVBoxLayout	*chanPassVBox = new QVBoxLayout();

	
	
	QLabel *chanNameLabel = new QLabel(tr("Name : "));
	_chanName = new QLineEdit();
	QHBoxLayout *chanNameHBox = new QHBoxLayout();
	chanNameHBox->addWidget(chanNameLabel);
	chanNameHBox->addWidget(_chanName);
	QLabel *chanDescLabel = new QLabel(tr("Description : "));
	_chanDesc = new QLineEdit();
	QHBoxLayout *chanDescHBox = new QHBoxLayout();
	chanDescHBox->addWidget(chanDescLabel);
	chanDescHBox->addWidget(_chanDesc);
	QLabel *chanMOTDLabel = new QLabel(tr("MOTD : "));
	_chanMOTD = new QLineEdit();
	QHBoxLayout *chanMOTDHBox = new QHBoxLayout();
	chanMOTDHBox->addWidget(chanMOTDLabel);
	chanMOTDHBox->addWidget(_chanMOTD);
	QLabel *editPassLabel = new QLabel(tr("Edit Password : "));
	_editPass = new QCheckBox();
	connect(_editPass, SIGNAL(stateChanged(int)), this, SLOT(enableChangePass(int)));
	QHBoxLayout *editPassHBox = new QHBoxLayout();
	editPassHBox->addWidget(editPassLabel);
	editPassHBox->addWidget(_editPass);

	QLabel *chanPassLabel = new QLabel(tr("Password : "));
	_chanPass = new QLineEdit();
	_chanPass->setEchoMode(QLineEdit::Password);
	_chanPass->setDisabled(true);
	QHBoxLayout *chanPassHBox = new QHBoxLayout();
	chanPassHBox->addWidget(chanPassLabel);
	chanPassHBox->addWidget(_chanPass);
	QLabel *chanConPassLabel = new QLabel(tr("Confirm Password : "));
	_chanConPass = new QLineEdit();
	_chanConPass->setDisabled(true);
	_chanConPass->setEchoMode(QLineEdit::Password);
	QHBoxLayout *chanConPassHBox = new QHBoxLayout();
	chanConPassHBox->addWidget(chanConPassLabel);
	chanConPassHBox->addWidget(_chanConPass);

	chanInfoVBox->addLayout(chanNameHBox);
	chanInfoVBox->addLayout(chanDescHBox);
	chanInfoVBox->addLayout(chanMOTDHBox);
	chanInfoBox->setLayout(chanInfoVBox);

	chanPassVBox->addLayout(editPassHBox);
	chanPassVBox->addLayout(chanPassHBox);
	chanPassVBox->addLayout(chanConPassHBox);
	chanPassBox->setLayout(chanPassVBox);

	page1Layout->addWidget(chanInfoBox,0, 0, 1, 3);
	page1Layout->addWidget(chanPassBox,0, 3, 1, 3);
	page1Layout->addWidget(buttonSaveChan, 1, 2, 1, 2);
	page1->setLayout(page1Layout);

	

		// Page 2
			QGridLayout *page2Layout = new QGridLayout;
			listUserRight = new QListWidget(page2);
			connect(listUserRight, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(selectUser(QListWidgetItem *, QListWidgetItem *)));
			listUserRightRights = new QListWidget(page2);
			saveRights = new QPushButton(tr("Save"));
			connect(saveRights, SIGNAL(clicked()), this, SLOT(saveChanRight()));
			page2Layout->addWidget(listUserRight,0, 0, 1, 3);
			page2Layout->addWidget(listUserRightRights,0, 3, 1, 3);
			page2Layout->addWidget(saveRights, 1, 2, 1, 2);
			page2->setLayout(page2Layout);

			// Page 3
		QGridLayout *page3Layout = new QGridLayout;
		QLabel *userBannedLabel = new QLabel(page1);
		userBannedLabel->setText("Users Banned :");
		QLabel *userNotBannedLabel = new QLabel(page1);
		userNotBannedLabel->setText("Users Not Banned :");
		listUserNotBanned = new QListWidget(this);
		connect(listUserNotBanned, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(selectNotBannedUser(QListWidgetItem *, QListWidgetItem *)));
		listUserBanned = new QListWidget(this);
		connect(listUserBanned, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(selectBannedUser(QListWidgetItem *, QListWidgetItem *)));
		banUserButton = new QPushButton(tr(">>"));
		connect(banUserButton, SIGNAL(clicked()), this, SLOT(banUser()));
		unbanUserButton = new QPushButton(tr("<<"));
		connect(unbanUserButton, SIGNAL(clicked()), this, SLOT(unbanUser()));
		page3Layout->addWidget(userNotBannedLabel, 0, 0, 1, 4);
		page3Layout->addWidget(listUserNotBanned, 1, 0, 10, 4);
		page3Layout->addWidget(userBannedLabel, 0, 5, 1, 4);
		page3Layout->addWidget(listUserBanned, 1, 5, 10, 4);
		page3Layout->addWidget(banUserButton, 5, 4, 1, 1);
		page3Layout->addWidget(unbanUserButton, 6, 4, 1, 1);
		page3->setLayout(page3Layout);

	// Ajout des onglets au QTabWidget, en indiquant la page qu'ils contiennent
    onglets->addTab(page1, "General");
	onglets->addTab(page2, "User's rights");
	onglets->addTab(page3, "Users banned");
	connect(onglets, SIGNAL(currentChanged(int)), this, SLOT(reloadUserList(int)));
	connect(this, SIGNAL(reload(int)), this, SLOT(reloadUserList(int)));
	connect(this, SIGNAL(SetChannelSig(IChannel*)), this, SLOT(SetChannelGUI(IChannel*)));
}

void ChannelPropertiesWindow::reload()
{
	emit this->SetChannelSig(this->_channel);
	emit this->reload(1);
	emit this->reload(2);
}

void ChannelPropertiesWindow::reloadUserList(int tab)
{
	Main* main = dynamic_cast<Main*>(this->_parent);
	if (tab == 1)
	{
		bool notEmpty = false;
		
		std::map<unsigned int, IUser*>::iterator it = main->_mapIdIUser.begin();
		std::map<unsigned int, IUser*>::iterator itend = main->_mapIdIUser.end();
		this->listUserRight->clear();
		for(;it != itend; ++it)
		{
			notEmpty = true;
			this->listUserRight->addItem(new QListWidgetItem(*(main->iconPeople),(*it).second->GetLogin().c_str(), 0, (*it).first));
		}
		if (notEmpty)
		{
			if (!this->listUserRight->item(0)->isSelected())
				this->listUserRight->item(0)->setSelected(true);
			selectUser(this->listUserRight->item(0), 0);
			listUserRightRights->setEnabled(this->_channel && main->_channelRights[this->_channel->GetId()]->GetCanEditUserRight()
				|| main->_hostRight->GetCanEditUser());
		}
		else
		{
			listUserRightRights->setEnabled(false);
		}
		
	}
	else if (tab == 2)
	{
		std::map<unsigned int, IUser*>::iterator it = main->_mapIdIUser.begin();
		std::map<unsigned int, IUser*>::iterator itend = main->_mapIdIUser.end();
		this->listUserNotBanned->clear();
		this->listUserBanned->clear();
		bool listUserNotBannedNotEmpty = false;
		bool listUserBannedNotEmpty = false;
		if (this->_channel)
			for(;it != itend; ++it)
			{
				if (main->IsBanned((*it).first, this->_channel->GetId()))
				{
					this->listUserBanned->addItem(new QListWidgetItem(*(main->iconPeople),(*it).second->GetLogin().c_str(), 0, (*it).first));
					listUserBannedNotEmpty = true;
				}
				else
				{
					this->listUserNotBanned->addItem(new QListWidgetItem(*(main->iconPeople),(*it).second->GetLogin().c_str(), 0, (*it).first));
					listUserNotBannedNotEmpty = true;
				}
			}
		if (listUserBannedNotEmpty)
		{
			this->listUserBanned->setItemSelected(this->listUserBanned->item(0), true);
			selectBannedUser(this->listUserBanned->item(0), 0);
		}
		if (listUserNotBannedNotEmpty)
		{
			this->listUserNotBanned->setItemSelected(this->listUserNotBanned->item(0), true);
			selectNotBannedUser(this->listUserNotBanned->item(0), 0);
		}
		bool enabled = main->IsConnected() && this->_channel && main->_channelRights.count(this->_channel->GetId()) && main->_channelRights[this->_channel->GetId()]->GetCanBanUser();
		this->banUserButton->setEnabled(enabled && listUserNotBannedNotEmpty);
		this->unbanUserButton->setEnabled(enabled && listUserBannedNotEmpty);
	}
	else if (tab == 0)
	{
		SetChannel(this->_channel);
	}
}

void ChannelPropertiesWindow::addRights(const char *txt)
{
	QListWidgetItem* test = new QListWidgetItem(txt);
	test->setCheckState(Qt::Unchecked);
	this->listUserRightRights->addItem(test);
}

void ChannelPropertiesWindow::initRightsList()
{
	addRights("Can Create Channel Child");
	addRights("Can Delete Channel Child");
	addRights("Can Edit Channel");
	addRights("Can Edit User Rights");
	addRights("Can Talk Channel");
	addRights("Can Write Channel");
	addRights("Can Kick User");
	addRights("Can Ban User");
	listUserRightRights->setDisabled(true);
}


void ChannelPropertiesWindow::setRights(unsigned int row, bool checked)
{
	if (checked)
		listUserRightRights->item(row)->setCheckState(Qt::Checked);
	else
		listUserRightRights->item(row)->setCheckState(Qt::Unchecked);
}


void ChannelPropertiesWindow::selectUser(QListWidgetItem *current, QListWidgetItem *)
{
	Main* main = dynamic_cast<Main*>(this->_parent);
	
	if (current && this->_channel)
	{
		IChannelRight *rights = main->_userChannelRights[current->type()][this->_channel->GetId()];
		this->_userIdforRights = current->type();
		if (rights)
		{
			setRights(0, rights->GetCanCreateChannelChild());
			setRights(1, rights->GetCanDeleteChannelChild());
			setRights(2, rights->GetCanEditChannel());
			setRights(3, rights->GetCanEditUserRight());
			setRights(4, rights->GetCanTalkChannel());
			setRights(5, rights->GetCanWriteChannel());
			setRights(6, rights->GetCanKickUser());
			setRights(7, rights->GetCanBanUser());
		}
	}
	else
		this->_userIdforRights = 0;
	
}

void			ChannelPropertiesWindow::enableChangePass(int)
{
	if (_editPass->isChecked())
	{
		this->_chanPass->setEnabled(true);
		this->_chanConPass->setEnabled(true);
	}
	else
	{
		this->_chanPass->setText("");
		this->_chanConPass->setText("");
		this->_chanPass->setEnabled(false);
		this->_chanConPass->setEnabled(false);
	}
}


void ChannelPropertiesWindow::SetChannel(IChannel* channel)
{
	emit this->SetChannelSig(channel);
}

void ChannelPropertiesWindow::SetChannelGUI(IChannel* channel)
{
	this->_channel = channel;
	if (channel)
	{
		QString title("'s Properties");
		this->setWindowTitle(title.prepend(channel->GetName().c_str()));
		Main* main = dynamic_cast<Main*>(this->_parent);
		IChannelRight *rights = main->_channelRights[this->_channel->GetId()];
		bool canEdit = (rights && rights->GetCanEditChannel());
		_chanName->setEnabled(canEdit);
		_chanDesc->setEnabled(canEdit);
		_chanMOTD->setEnabled(canEdit);
		_chanPass->setEnabled(canEdit && _editPass->isChecked());
		_chanConPass->setEnabled(canEdit && _editPass->isChecked());
		_editPass->setEnabled(canEdit);

		this->_chanName->setText(channel->GetName().c_str());
		this->_chanDesc->setText(channel->GetDescription().c_str());
		this->_chanMOTD->setText(channel->GetMotd().c_str());
		this->reloadUserList(1);
	}
	else
	{
		this->close();
		this->_chanName->setText("");
		this->_chanDesc->setText("");
		this->_chanMOTD->setText("");
		_chanName->setEnabled(false);
		_chanDesc->setEnabled(false);
		_chanMOTD->setEnabled(false);
		_chanPass->setEnabled(false);
		_chanConPass->setEnabled(false);
		_editPass->setEnabled(false);
	}
}


void ChannelPropertiesWindow::saveChanRight()
{
	Main* main = dynamic_cast<Main*>(this->_parent);
	if (!this->_channel)
		return;
	IChannelRight *rights = main->_userChannelRights[this->_userIdforRights][this->_channel->GetId()];

	if (rights)
	{
		rights->SetCanCreateChannelChild(listUserRightRights->item(0)->checkState() == Qt::Checked);
		rights->SetCanDeleteChannelChild(listUserRightRights->item(1)->checkState() == Qt::Checked);
		rights->SetCanEditChannel(listUserRightRights->item(2)->checkState() == Qt::Checked);
		rights->SetCanEditUserRight(listUserRightRights->item(3)->checkState() == Qt::Checked);
		rights->SetCanTalkChannel(listUserRightRights->item(4)->checkState() == Qt::Checked);
		rights->SetCanWriteChannel(listUserRightRights->item(5)->checkState() == Qt::Checked);
		rights->SetCanKickUser(listUserRightRights->item(6)->checkState() == Qt::Checked);
		rights->SetCanBanUser(listUserRightRights->item(7)->checkState() == Qt::Checked);
		AgoraClient::AdminManager::GetAdminManager()->SetUserChannelRight(this->_channel->GetId(), this->_userIdforRights, rights);

	}
}

void			ChannelPropertiesWindow::saveChan()
{
	if (!this->_channel)
		return;
	if (_chanPass->text() == _chanConPass->text())
	{
		this->_channel->SetName(_chanName->text().toStdString());
		this->_channel->SetDescription(_chanDesc->text().toStdString(), false);
		this->_channel->SetMotd(_chanMOTD->text().toStdString(), false);
		this->_channel->SetPassword(_chanPass->text().toStdString(), false);
		AgoraClient::AdminManager::GetAdminManager()->SaveChannelChangements(this->_channel, this->_editPass->isChecked());
	}
	else
		QMessageBox::information(0, "Error", "You have made some mistakes in the password");
}

void			ChannelPropertiesWindow::banUser()
{
	if (!this->_channel)
		return;
	AgoraClient::AdminManager::GetAdminManager()->BanUser(_userIdforUserNotBanned, this->_channel->GetId());
}

void			ChannelPropertiesWindow::unbanUser()
{
	if (!this->_channel)
		return;
	AgoraClient::AdminManager::GetAdminManager()->UnbanUser(_userIdforUserBanned, this->_channel->GetId());
}

void			ChannelPropertiesWindow::selectNotBannedUser(QListWidgetItem *current, QListWidgetItem *)
{
	if (current)
		this->_userIdforUserNotBanned = current->type();
}

void			ChannelPropertiesWindow::selectBannedUser(QListWidgetItem *current, QListWidgetItem *)
{
	if (current)
		this->_userIdforUserBanned = current->type();
}

IChannel *ChannelPropertiesWindow::GetChannel()
{
	return this->_channel;
}